<template>
    <div>
      <el-form :model="form" label-width="120px">
        <el-form-item label="省份">
          <el-select v-model="form.provinceId" placeholder="请选择省份" @change="handleProvinceChange">
            <el-option v-for="item in provinces" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
          </el-select>
        </el-form-item>
        <el-form-item label="城市">
          <el-select v-model="form.cityId" placeholder="请选择城市" @change="handleCityChange" :disabled="!form.provinceId">
            <el-option v-for="item in cities" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
          </el-select>
        </el-form-item>
        <el-form-item label="区/县">
          <el-select v-model="form.districtId" placeholder="请选择区/县" :disabled="!form.cityId">
            <el-option v-for="item in districts" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script>
  import { getAddress } from '@/api/address'
  
  export default {
    name: 'AddressSelector',
    data() {
      return {
        form: {
          provinceId: '',
          cityId: '',
          districtId: ''
        },
        provinces: [],
        cities: [],
        districts: []
      }
    },
    created() {
      this.getProvinces()
    },
    methods: {
      async getProvinces() {
        try {
          const res = await getAddress(0, 0)
          this.provinces = res.data
        } catch (error) {
          console.error('获取省份失败', error)
        }
      },
      async handleProvinceChange(provinceId) {
        this.form.cityId = ''
        this.form.districtId = ''
        this.cities = []
        this.districts = []
        try {
          const res = await getAddress(provinceId, 1)
          this.cities = res.data
        } catch (error) {
          console.error('获取城市失败', error)
        }
      },
      async handleCityChange(cityId) {
        this.form.districtId = ''
        this.districts = []
        try {
          const res = await getAddress(cityId, 2)
          this.districts = res.data
        } catch (error) {
          console.error('获取区/县失败', error)
        }
      }
    }
  }
  </script>